<?php

class PlayerHistoryTable extends Doctrine_Table
{
    public function getBackendList(Doctrine_Query $q)
    {
        $rootAlias = $q->getRootAlias();
        $q->leftJoin($rootAlias.".Raid raid")
                ->leftJoin($rootAlias.".Player p");
        return $q;
    }

    public function updatePoints($playerid = -1, $raidid = -1, $withAttendance = false)
    {
        //Doctrine::getTable("Guildhistory")->refresh();
        ini_set('memory_limit', '128M');
        $allPlayers = ($playerid > -1 ? 0 : 1);
        $allRaids = ($raidid > -1 ? 0 : 1);

        $playerList = array();
        $raidList = array();

        if ($allPlayers)
        {
            $q = Doctrine::getTable("Player")
                    ->getGuildedPlayerList()
                    ->select('id');
            $playerRes = $q->execute();

            foreach ($playerRes as $player)
            {
                $playerList[] = $player->getId();
                $player->free(true);
                unset($player);
            }
            $q->free(true);
            unset($q);
            $playerRes->free(true);
            unset($playerRes);
        }
        else
        {
            $playerList[] = $playerid;
        }
        //print_r($playerList);

        if ($allRaids)
        {
            $q = Doctrine::getTable("Raid")
                    ->getRaidList()
                    ->select('id');
            $raidRes = $q->execute();

            foreach ($raidRes as $raid)
            {
                $raidList[] = $raid->getId();
                $raid->free(true);
                unset($raid);
            }
            $q->free(true);
            unset($q);
            $raidRes->free(true);
            unset($raidRes);
        }
        else
        {
            $raidList[]  = $raidid;
        }

        foreach ($raidList as $raid)
        {
            $q2 = Doctrine::getTable("History")
                ->createQuery()
                ->select('playerid')
                ->where("raidid=?", $raid)
                ->andWhereIn("playerid", $playerList)
                ->groupBy("playerid");
            $r2 = $q2->execute();
            foreach ($r2 as $p)
            {

                $player = $p['playerid'];

                $q = Doctrine::getTable("PlayerHistory")
                    ->createQuery()
                    ->select()
                    ->where("playerid=?", $player)
                    ->andWhere("raidid=?", $raid);
                $r = $q->execute();
                $ph = null;

                if ($r->count() == 1)
                {
                    $ph = $r->getFirst();
                }
                else
                {
                    $ph = new PlayerHistory();
                    $ph->setRaidid($raid);
                    $ph->setPlayerid($player);
                }

                $points = 0;

                $query = Doctrine::getTable("History")
                    ->createQuery()
                    ->select("SUM(value)")
                    ->where("playerid=?", $player)
                    ->andWhere("raidid=?", $raid);
                $result = $query->execute();
                $data = $result->getFirst()->toArray();
                if (isset($data["SUM"]))
                {
                    $points = $data["SUM"];
                }

                $lifetime = 0;

                $query = Doctrine::getTable("History")
                    ->createQuery()
                    ->select("SUM(value)")
                    ->where("playerid=?", $player)
                    ->andWhere("raidid=?", $raid)
                    ->andWhere("value > ?", 0)
                    ->andWhereIn("aaction", array("I", "U"));
                $result = $query->execute();
                $data = $result->getFirst()->toArray();
                if (isset($data["SUM"]))
                {
                    $lifetime = $data["SUM"];
                }

                $query = Doctrine::getTable("History")
                    ->createQuery()
                    ->select("SUM(value)")
                    ->where("playerid=?", $player)
                    ->andWhere("raidid=?", $raid)
                    ->andWhere("value > ?", 0)
                    ->andWhereIn("aaction", array("D"));
                $result = $query->execute();
                $data = $result->getFirst()->toArray();
                if (isset($data["SUM"]))
                {
                    $lifetime = $lifetime - $data["SUM"];
                }

                $ph->setPoints($points);
                $ph->setLifetime($lifetime);
                $ph->save();
//                if ($withAttendance)
//                {
//                    echo sfConfig::get('sf_root_dir')."/symfony raidpoints:updateAttendance ".$raid." ".$player."\n";
//                    system(sfConfig::get('sf_root_dir')."/symfony raidpoints:updateAttendance ".$raid." ".$player);
//                }

            }
        }
        $query = Doctrine::getTable("GuildHistory")
                ->createQuery('h')
                ->select('dt, scheduled_date, playerid, raidid')
                ->where('scheduled_date > ?', "0000-00-00")
                ->andWhere('scheduled_date IS NOT NULL')
                ->andWhere('ttype=?', 'P')
                ->orderBy('dt');
        echo $query->getDql();
        $result = $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();

        $master = array();
        $player = array();
        //print_r($result);
        //exit();
        $maxSD = 0;
        foreach ($result as $gh)
        {
            if (!isset($master[$gh['h_raidid']]))
            {
                $master[$gh['h_raidid']] = array();
                $player[$gh['h_raidid']] = array();
            }

//            if (!isset($master[$gh['h_raidid']][strtotime($gh['h_scheduled_date']." GMT")]))
//                $master[$gh['h_raidid']][strtotime($gh['h_scheduled_date']." GMT")] = array();

            if (!isset($master[$gh['h_raidid']][strtotime($gh['h_scheduled_date']." GMT")][$gh['h_dt']]))
                $master[$gh['h_raidid']][strtotime($gh['h_scheduled_date']." GMT")][$gh['h_dt']] = $gh['h_dt'];

            if (!isset($player[$gh['h_raidid']][$gh['h_playerid']]))
                $player[$gh['h_raidid']][$gh['h_playerid']] = array();

//            if (!isset($player[$gh['h_raidid']][$gh['h_playerid']][strtotime($gh['h_scheduled_date']." GMT")]))
//                $player[$gh['h_raidid']][$gh['h_playerid']][strtotime($gh['h_scheduled_date']." GMT")] = array();

            $player[$gh['h_raidid']][$gh['h_playerid']][strtotime($gh['h_scheduled_date']." GMT")][] = $gh['h_dt'];

            if (strtotime($gh['h_scheduled_date']." GMT") > $maxSD)
                $maxSD = strtotime($gh['h_scheduled_date']." GMT");
        }

        $maxAtt = 0;
        $attDays = explode(",",sfConfig::get("app_attendance_days"));
        foreach ($attDays as $days)
        {
            if ($days > $maxAtt)
                $maxAtt = $days;
        }
        $minSD = $maxSD - ($maxAtt * 60 * 60 * 24);


        $attArray = array();
        $masArray = array();
        $firstAtt = array();
        $masterLifetime = array();
        $playerLifetime = array();

        foreach ($player as $raidid => $raidid_data)
        {
            $firstAtt[$raidid] = array();
            foreach ($raidid_data as $playerid => $playerid_data)
            {
                $firstRaid = 0;
                foreach ($playerid_data as $scheduled_date => $scheduled_date_data)
                {
                    if ($firstRaid == 0 || $firstRaid > $scheduled_date)
                        $firstRaid = $scheduled_date;
                    if ($scheduled_date >= $minSD)
                    {
                        foreach ($attDays as $attDay)
                        {
                            if ($scheduled_date >= ($maxSD - ($attDay * 60 * 60 * 24)))
                            {
                                $attArray[$attDay][$raidid][$playerid][$scheduled_date] = count($scheduled_date_data);
                            }
                        }
                    }
                    $playerLifetime[$raidid][$playerid][$scheduled_date] = count($scheduled_date_data);
                }
                $firstAtt[$raidid][$playerid] = $firstRaid;
            }
        }

        foreach ($master as $raidid => $raidid_data)
        {
            foreach ($raidid_data as $scheduled_date => $scheduled_date_data)
            {
                if ($scheduled_date >= $minSD)
                {
                    foreach ($attDays as $attDay)
                    {
                        if ($scheduled_date >= ($maxSD - ($attDay * 60 * 60 * 24)))
                        {
                            $masArray[$attDay][$raidid][$scheduled_date] = count($scheduled_date_data);
                        }
                    }
                }
                $masterLifetime[$raidid][$scheduled_date] = count($scheduled_date_data);
            }
        }
        //print_r($master);
        //print_r($player);
        //print_r($attArray);

        echo "lifetime:\n";
        foreach ($firstAtt as $raidid => $raidid_data)
        {
            foreach ($raidid_data as $playerid => $firstRaid)
            {
                $pmLifetime = array();
                foreach ($masterLifetime[$raidid] as $scheduled_date => $scheduled_date_data)
                {
                    if ($scheduled_date >= $firstRaid)
                    {
                        $pmLifetime[$scheduled_date] = $scheduled_date_data;
                    }
                }
                echo "playerid: ".$playerid."\t".count($playerLifetime[$raidid][$playerid])."/".count($pmLifetime)."\t".round((count($playerLifetime[$raidid][$playerid])/count($pmLifetime))*100)."\n";
                $query = Doctrine::getTable("PlayerAttendance")
                        ->createQuery('pa')
                        ->select("id")
                        ->where("playerid=?", $playerid)
                        ->andWhere("raidid=?", $raidid)
                        ->andWhere("numdays=?", 0);
                $result = $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
                $pa = null;
                if ($result[0]['pa_id'])
                {
                    $query = Doctrine::getTable("PlayerAttendance")
                            ->createQuery('pa')
                            ->update()
                            ->set("percent", round((count($playerLifetime[$raidid][$playerid])/count($pmLifetime))*100))
                            ->where("playerid=?", $playerid)
                            ->andWhere("raidid=?", $raidid)
                            ->andWhere("numdays=?", 0);
                    $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
                }
                else
                {
                    $pa = new PlayerAttendance();
                    $pa->setRaidid($raidid);
                    $pa->setPlayerid($playerid);
                    $pa->setNumdays(0);
                    $pa->setPercent(round((count($playerLifetime[$raidid][$playerid])/count($pmLifetime))*100));
                    $pa->save();
                }
            }
        }

        foreach ($attArray as $attDay => $attData)
        {
            echo "attDay: ".$attDay."\n";
            foreach ($attData as $raidid => $raidid_data)
            {
                foreach ($raidid_data as $playerid => $playerid_data)
                {
                    echo "playerid: ".$playerid."\t".count($playerid_data)."/".count($masArray[$attDay][$raidid])."\t".round((count($playerid_data)/count($masArray[$attDay][$raidid]))*100)."\n";

                    $query = Doctrine::getTable("PlayerAttendance")
                            ->createQuery('pa')
                            ->select("id")
                            ->where("playerid=?", $playerid)
                            ->andWhere("raidid=?", $raidid)
                            ->andWhere("numdays=?", $attDay);
                    $result = $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
                    $pa = null;
                    if ($result[0]['pa_id'])
                    {
                        $query = Doctrine::getTable("PlayerAttendance")
                                ->createQuery('pa')
                                ->update()
                                ->set("percent", round((count($playerid_data)/count($masArray[$attDay][$raidid]))*100))
                                ->where("playerid=?", $playerid)
                                ->andWhere("raidid=?", $raidid)
                                ->andWhere("numdays=?", $attDay);
                        $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
                    }
                    else
                    {
                        $pa = new PlayerAttendance();
                        $pa->setRaidid($raidid);
                        $pa->setPlayerid($playerid);
                        $pa->setNumdays($attDay);
                        $pa->setPercent(round((count($playerid_data)/count($masArray[$attDay][$raidid]))*100));
                        $pa->save();
                    }
                }

            }
        }

        $query = Doctrine::getTable("CachePlayerHistory")
                ->createQuery()->delete();
        $query->execute();

    }
}